package cn.hdu.dao.impl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.hdu.dao.UserDao;
import cn.hdu.domain.User;
import cn.hdu.util.DBCPUtil;

public class UserDaoImpl implements UserDao {
	QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());

	public void addUser(User user) {
		try {
			qr.update("insert into user (id, username, nickname, password, email, actived, code) values(?,?,?,?,?,?,?)",
					user.getId(), user.getUsername(), user.getNickname(), user.getPassword(),
					user.getEmail(), user.isActived(), user.getCode());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public User findUser(String username, String password) {
		try {
			return qr.query("select * from user where username=? and password=?", new BeanHandler<User>(User.class), username, password);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public User findUserByCode(String code) {
		try {
			return qr.query("select * from user where code=?", new BeanHandler<User>(User.class), code);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void updateUser(User user) {
		try {
			qr.update("update user set username=?, nickname=?, password=?, email=?, actived=?, code=? where id=?",
					user.getUsername(), user.getNickname(), user.getPassword(),
					user.getEmail(), user.isActived(), user.getCode(), user.getId());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
